package com.yangji.rxjavatest.rx.usertoken;


import com.yangji.rxjavatest.Log;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class UserTest {

    public UserTest() {

        getUserInfo()
                .onErrorResumeNext(new ObservableSource<UserInfo>() {
            @Override
            public void subscribe(Observer<? super UserInfo> observer) {
                Log.d("onErrorResumeNext 1");
            }
        }).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends UserInfo>>() {
            @Override
            public ObservableSource<? extends UserInfo> apply(Throwable throwable) throws Exception {
                Log.d("onErrorResumeNext 2");
                throwable.printStackTrace();
                if (isHttp401Error(throwable)) {

                }
                return Observable.error(throwable);
            }

            public boolean isHttp401Error(Throwable throwable) {
                return throwable instanceof AccessDenyException;
            }
        }).subscribe(new Consumer<UserInfo>() {
            @Override
            public void accept(UserInfo userInfo) throws Exception {
                Log.d("accept" + userInfo.name);
            }
        });

    }


    Observable<TokenInfo> getToken() {
        return Observable.create(new ObservableOnSubscribe<TokenInfo>() {
            @Override
            public void subscribe(ObservableEmitter<TokenInfo> e) throws Exception {
                e.onNext(new TokenInfo());
                e.onError(new NullPointerException(""));
            }
        });
    }

    Observable<UserInfo> getUserInfo() {
        return Observable.create(new ObservableOnSubscribe<UserInfo>() {
            @Override
            public void subscribe(ObservableEmitter<UserInfo> e) throws Exception {
                e.onError(new NullPointerException(""));
            }
        });
    }

    class AccessDenyException extends Exception{

    }

    class UserInfo {

        public String name = "张三";

    }

    class TokenInfo {
        public String deviceToken = System.currentTimeMillis() + "";
    }

}
